package cn.yuanqiao.archive.Identify.service.impl;

import cn.yuanqiao.archive.Identify.domain.*;
import cn.yuanqiao.archive.Identify.mapper.BgqxIdentifyMapper;
import cn.yuanqiao.archive.Identify.mapper.DisposeMapper;
import cn.yuanqiao.archive.Identify.mapper.IsOpenIdentifyMapper;
import cn.yuanqiao.archive.Identify.service.DisposeNewService;
import cn.yuanqiao.archive.Identify.service.IDisposeService;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.danganzhengli.service.IHandOverDaService;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.impl.WenjianzhengliServiceImpl;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.BusinessActivity;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.enums.BusinessBehavior;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.util.BusinessBehaviorUtil;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.system.service.ISysUserService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.yuanqiao.common.utils.PageUtils.startPage;


/**
 * @ProjectName: cn.yuanqiao.archive.Identify.service.impl
 * @ClassName: DisposeNewServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/10/16 17:39
 * @Version: 1.0
 **/
@Service
public class DisposeNewServiceImpl implements DisposeNewService {
    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Autowired
    private WenjianzhengliServiceImpl wenjianzhengliService;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private BgqxIdentifyMapper bgqxIdentifyMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private IsOpenIdentifyMapper isOpenIdentifyMapper;
    @Autowired
    private ISysUserService remoteUserService;
    @Autowired
    private IsOpenIdentifyServiceImpl isOpenIdentifyserviceimpl;
    @Autowired
    private TenantYqdaFolderMapper yqdaFolderMapper;
    @Autowired
    private ITenantSysDictTypeService dictTypeService;
    @Autowired
    private ITenantCateMdataListService cateMdataListService;
    @Autowired
    private IDisposeService disposeService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private TenantMijiComparisonTableServiceImpl mijiComparisonTableService;

    @Autowired
    private DisposeMapper disposeMapper;
    @Autowired
    private IHandOverDaService handOverDaService;
    @Autowired
    private ITenantCategoryService tenantCategoryService;

    private String dataBaseId;

    @PostConstruct
    public void getDatabaseId() {
        dataBaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
    }

    /**
     * 列表
     * @param json
     * @return
     */
    @Override
    public List<Map<String, Object>> getlist(JSONObject json) {
        String fields = "ID," + json.getString("fields");//需要查询的字段
        Long categoryId = json.getLong("categoryId");//门类id
        Long menuId = json.getLong("menuId");//菜单id
        String subTableName = json.getString("subTableName");//层级节点的表名
//        JSONArray propertyName = json.getJSONArray("propertyName");//分类节点的属性
//        JSONArray propertyValue = json.getJSONArray("propertyValue");//分类节点的值
        //Long fondsId=json.getLong("fondsId");//全宗id
       // String fields = "(select to_char(wm_concat((case cztype when 'bgqx' then '保管期限' when 'yijiao' then '移交' when 'xiaohui' then '销毁' else '' end))) from " + SecurityUtils.getTenantCode() + "_dispose where   da_id = id) AS cztype,ID," + json.getString("fields");//需要查询的字段
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        StringBuilder sb = new StringBuilder(" and ");//用于拼接条件
        String orderstr = json.getString("order");//用于排序
        int type = -1;
        /**处理查询条件*/
        if (null == jsonArray) {
            jsonArray = new JSONArray();
        }

        if (FBswitch) {
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            sb.append(" MJ in ('" + getdamjbyrymj.stream().map(m -> m.getDaMj()).collect(Collectors.joining("','")) + "') and ");
        }

        if (jsonArray.size() > 0) {
            wenjianzhengliService.concatQueryCondition(jsonArray, sb);
        }
        /**处理表名*/
        TenantCategory category = new TenantCategory();
        String tablename = "";
        if (null != subTableName && !"".equals(subTableName)) {//有层级信息
            tablename = subTableName;
            String tablenametype = subTableName.substring(subTableName.length() - 3, subTableName.length() - 2);
            if ("F".equalsIgnoreCase(tablenametype)) {//档案层
                type = 0;
            } else if ("V".equalsIgnoreCase(tablenametype)) {//案卷层
                type = 1;
            } else if ("X".equalsIgnoreCase(tablenametype)) {//项目层
                type = 1;
                tablename = subTableName.substring(0, subTableName.length() - 3) + "V" + subTableName.substring(subTableName.length() - 2, subTableName.length());
            } else if ("E".equalsIgnoreCase(tablenametype)) {//电子文件层
                type = 2;
            }
        } else {
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            if (tenantCategory.getType() == 0) {//件
                tablename = tenantCategory.getFileTableName();
            } else if (tenantCategory.getType() == 1) {//卷
                tablename = tenantCategory.getFolderTableName();
            } else if (tenantCategory.getType() == 2) {//电子文件
                tablename = tenantCategory.getEfileTableName();
            } else if (tenantCategory.getType() == 3) {//项目
                tablename = tenantCategory.getFolderTableName();
            }
            type = tenantCategory.getType();
            if (3 == type) {
                type = 1;
            }
        }
        /**处理分类值*/
//        if (propertyName.size() > 0) {
//            for (int i = 0; i < propertyName.size(); i++) {
//                sb.append(" " + propertyName.get(i) + " = " + "'" + propertyValue.get(i) + "' and ");
//            }
//        }
        String tiaojian = sb.toString();
        /**处理拼接条件时的sql*/
        if (tiaojian.endsWith("and ")) {
            tiaojian = tiaojian.substring(0, tiaojian.length() - 4);
        } else if (tiaojian.endsWith("and")) {
            tiaojian = tiaojian.substring(0, tiaojian.length() - 3);
        }
        /**处理排序*/
        if (null != orderstr && !"".equals(orderstr)) {
            orderstr = " order by " + orderstr;
        } else {
            String applyorderstr = tenantMdataListService.getorder(categoryId, menuId, type);
            if (null != applyorderstr && !"".equals(applyorderstr)) {
                orderstr = " order by " + applyorderstr;
            }
        }
        startPage();
        /** 拼接条件(bgqx到期/未鉴定过/已在流程中) */
        /*bgqx到期*/
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowdate = sdf.format(date);
        String bgqxgqsql = "";
        //2024-10-14 按年度判断过期,目前只修改了瀚高数据库 赵常飞
        if (dataBaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
            bgqxgqsql = "select id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,rq,jdsj," +
                    "to_char(TO_DATE((case when jdsj is null then (case  when RQ IS NOT NULL then rq else '19000101'  end) " +
                    "else jdsj end ), case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END),'YYYYMMDD') as formatrq,(to_char(TO_DATE((case when jdsj is null then (case " +
                    " when RQ IS NOT NULL then rq else '19000101'  end) else jdsj end )," +
                    " case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END)+replace(bgqx, 'D', '')*365,'YYYYMMDD')) as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ') where gqsj<='" + nowdate + "'";
        } else if (dataBaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || dataBaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())) {
            bgqxgqsql = "select id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,nd,jdsj," +
                    "to_char(TO_DATE((case when jdsj is null then (case  when nd IS NOT NULL then nd else '1900'  end) " +
                    "else jdsj end ), 'YYYY' ),'YYYY') as formatrq,(to_char(TO_DATE((case when jdsj is null then (case " +
                    " when nd IS NOT NULL then nd else '1900'  end) else jdsj end )," +
                    " 'YYYY')+cast(replace(bgqx,'D','')+1 as integer)*365,'YYYYMMDD')) as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ' ) where gqsj<='" + nowdate + "'";
        } else {

            bgqxgqsql = "select /*+ENABLE_IN_VALUE_LIST_OPT(0)*/ id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,rq,jdsj,DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD') as formatrq,(DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD')+replace(bgqx, 'D', '')*10000)as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ')where gqsj<='" + nowdate + "'";
        }
        /*未鉴定过*/
        tiaojian += " and ( ";
        //不在保管期限和销毁流程中
        TenantYqbgqxjdJobDa yqbgqxjdJobDa = new TenantYqbgqxjdJobDa();
        TenantYqbgqxjdJob yqbgqxjdJob = new TenantYqbgqxjdJob();
        TenantYqxhjdJobDa yqxhjdJobDa = new TenantYqxhjdJobDa();
        TenantYqxhjdJob yqxhjdJob = new TenantYqxhjdJob();
        String lczsql = " (select daid from " + yqbgqxjdJobDa.getTableName() + " where renwuid in(select id from " + yqbgqxjdJob.getTableName() + " where is_del=0 and jiandingstate!=9 and jiandingstate!=8))union(select DA_ID from " + new TenantDispose().getTableName() + " where CZTYPE='xiaohui')";//未撤销且鉴定未完成
        /**查询列表并返回*/
        return isOpenIdentifyMapper.getlist(new DataScopeBase(menuId),fields, tablename, bgqxgqsql, lczsql, tiaojian, orderstr, "cztype");
    }

    /**
     * 添加档案到任务
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addArchive(JSONObject json) {
        List ids=json.getJSONArray("ids");
        Long categoryId=json.getLong("categoryId");
        Long renwuid = json.getLong("renwuid");
        String type="bgqx";
        for (int i = 0; i < ids.size(); i++) {
            TenantDispose dispose=new TenantDispose();
            dispose.setDaId(Long.parseLong(String.valueOf(ids.get(i))));
            dispose.setCztype(type);
            dispose.setCategoryId(categoryId);
            List<Long> idss=new ArrayList<>(1);
            idss.add(Long.parseLong(String.valueOf(ids.get(i))));
            deletedata(idss,type);
            disposeMapper.fpcz(dispose);
        }
        TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        //查询此条数据是否已经存在于此任务中,存在时直接跳过
        List<String> jobdaids = tenantCategoryMapper.getdaidsbyrenwuid(renwuid, new TenantYqbgqxjdJobDa().getTableName());
        if (category.getType() == 0) {//件
            for (int i = 0; i < ids.size(); i++) {
                if (jobdaids.contains(String.valueOf(ids.get(i)))) {
                    continue;
                }
                String   tablename = SecurityUtils.getTenantCode() + Constants.BIG_TABLE_YQDA;
                List<String> strings = isOpenIdentifyMapper.selectString(" BGQX ", " select BGQX from " + tablename + " where DA_ID = '" + ids.get(i) + "' ");
                TenantYqbgqxjdJobDa yqbgqxjdJobDa = new TenantYqbgqxjdJobDa();
                yqbgqxjdJobDa.setRenwuid(renwuid);
                yqbgqxjdJobDa.setDaid(Long.parseLong(String.valueOf(ids.get(i))));
                yqbgqxjdJobDa.setType("f");
                if (strings != null && strings.size() > 0 &&strings.get(0)!= null)yqbgqxjdJobDa.setPrimevalBgqx(strings.get(0));
                bgqxIdentifyMapper.insertda(yqbgqxjdJobDa);
            }
        } else if (category.getType() == 1) {//卷
            for (int i = 0; i < ids.size(); i++) {
                if (jobdaids.contains(String.valueOf(ids.get(i)))) {
                    continue;
                }
                String   tablename = SecurityUtils.getTenantCode() + Constants.BIG_TABLE_YQFOLDER;
                List<String> strings = isOpenIdentifyMapper.selectString(" BGQX ", " select BGQX from " + tablename + " where FOLDER_ID = '" + ids.get(i) + "' ");
                //添加卷层
                TenantYqbgqxjdJobDa yqbgqxjdJobDa = new TenantYqbgqxjdJobDa();
                yqbgqxjdJobDa.setRenwuid(renwuid);
                yqbgqxjdJobDa.setDaid(Long.parseLong(String.valueOf(ids.get(i))));
                yqbgqxjdJobDa.setType("v");
                if (strings != null && strings.size() > 0 &&strings.get(0)!= null)yqbgqxjdJobDa.setPrimevalBgqx(strings.get(0));
                bgqxIdentifyMapper.insertda(yqbgqxjdJobDa);
                TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
                List<String> daids = yqdaFolderMapper.selectFileIdByFolderId1(String.valueOf(ids.get(i)), yqdaFolder.getTableName(), new TenantYqda().getTableName());
                for (int j = 0; j < daids.size(); j++) {
                    TenantYqbgqxjdFolderDa yqbgqxjdFolderDa = new TenantYqbgqxjdFolderDa();
                    yqbgqxjdFolderDa.setRenwuid(renwuid);
                    yqbgqxjdFolderDa.setDaid(Long.parseLong(String.valueOf(daids.get(j))));
                    yqbgqxjdFolderDa.setType("v_f");
                    yqbgqxjdFolderDa.setVid(Long.parseLong(String.valueOf(ids.get(i))));
                    bgqxIdentifyMapper.insertfolderda(yqbgqxjdFolderDa);
                }
            }
        } else if (category.getType() == 3) {//项目
            for (int i = 0; i < ids.size(); i++) {
                if (jobdaids.contains(String.valueOf(ids.get(i)))) {
                    continue;
                }
                String   tablename = SecurityUtils.getTenantCode() + Constants.BIG_TABLE_YQITEM;
                List<String> strings = isOpenIdentifyMapper.selectString(" BGQX ", " select BGQX from " + tablename + " where ITEM_ID = '" + ids.get(i) + "' ");
                //添加项目
                TenantYqbgqxjdJobDa yqbgqxjdJobDa = new TenantYqbgqxjdJobDa();
                yqbgqxjdJobDa.setRenwuid(renwuid);
                yqbgqxjdJobDa.setDaid(Long.parseLong(String.valueOf(ids.get(i))));
                yqbgqxjdJobDa.setType("v");
                if (strings != null && strings.size() > 0 &&strings.get(0)!= null)yqbgqxjdJobDa.setPrimevalBgqx(strings.get(0));
                bgqxIdentifyMapper.insertda(yqbgqxjdJobDa);
                TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
                List<String> daids = yqdaFolderMapper.selectFileIdByFolderId1(String.valueOf(ids.get(i)), yqdaFolder.getTableName(), new TenantYqda().getTableName());
                for (int j = 0; j < daids.size(); j++) {
                    TenantYqbgqxjdFolderDa yqbgqxjdFolderDa = new TenantYqbgqxjdFolderDa();
                    yqbgqxjdFolderDa.setRenwuid(renwuid);
                    yqbgqxjdFolderDa.setDaid(Long.parseLong(String.valueOf(daids.get(j))));
                    yqbgqxjdFolderDa.setType("v_f");
                    yqbgqxjdFolderDa.setVid(Long.parseLong(String.valueOf(ids.get(i))));
                    bgqxIdentifyMapper.insertfolderda(yqbgqxjdFolderDa);
                }
            }
        }
//        disposeService.deletedata(ids, "bgqx");

        return 1;
    }
    @Override
    public String updateshending(JSONObject json) {
        String level = json.getString("level");
        String type = json.getString("type");
        Long renwuid = json.getLong("renwuid");
        Long daid = json.getLong("daid");
        String jdvalue = json.getString("jdvalue");
        String fsvale = json.getString("fsvalue");
        String state = "1";
        String jiandingfield = "";
        String jiandingstate = "";
        String chuzhifangsshi ="";
        if ("chushen".equals(type)) {
            jiandingfield = "CHUSHEN_JIANDING";
            jiandingstate = "CHUSHEN_STATE";
            chuzhifangsshi = "CHUSHEN_CHUZHIFANGSHI";
        } else {
            jiandingfield = "FUSHEN_JIANDING";
            jiandingstate = "FUSHEN_STATE";
            chuzhifangsshi = "FUSHEN_CHUZHIFANGSHI";
        }
        if ("1".equals(fsvale)&& StringUtils.isEmpty(jdvalue)) {
            state = "0";
        }
        String tableName = "";
        if ("v_f".equals(level)) {//卷内件
            tableName = new TenantYqbgqxjdFolderDa().getTableName();
        } else {//说明是最外层 可能是f v x
            tableName = new TenantYqbgqxjdJobDa().getTableName();
            if ("f".equals(level) || "DQ".equals(jdvalue) || "CQ".equals(jdvalue)) {//件直接审
            } else if ("v".equals(level)) {//案卷判断卷内件
                //案卷需要判断卷内件是否已经鉴定
                int i = isOpenIdentifyMapper.getjiandingnum(new TenantYqbgqxjdFolderDa().getTableName(), renwuid, daid, jiandingstate);
                if (i > 0) {
                    return "此案卷中存在未经" + ("chushen".equals(type) ? "初审" : "复审") + "过的档案!";
                }
                //获取卷内件最大bgqx
                String maxjnjbgqx = bgqxIdentifyMapper.getmaxjnjbgqx(new TenantYqbgqxjdFolderDa().getTableName(), renwuid, jiandingfield, daid);
                if ((null == maxjnjbgqx || "".equals(maxjnjbgqx)) && StringUtils.isEmpty(fsvale)) {
                    return "卷内件未审查!";
                }
                if ("Y".equals(maxjnjbgqx)) {
                    maxjnjbgqx = "999";
                }
                if ("Y".equals(jdvalue)) {
                    jdvalue = "999";
                }
                if (!"DQ".equals(jdvalue) && !"CQ".equals(jdvalue) && !"DQ".equals(maxjnjbgqx) && !"CQ".equals(maxjnjbgqx) && StringUtils.isEmpty(fsvale)) {
                    if (StringUtils.isNotEmpty(jdvalue) &&qcint(maxjnjbgqx) > qcint(jdvalue)) {
                        return "案卷的保管期限不能小于卷内档案的保管期限!";
                    }
                }else {
                    String maxchuzhifangsshi = bgqxIdentifyMapper.getmaxjnjbgqx(new TenantYqbgqxjdFolderDa().getTableName(), renwuid, chuzhifangsshi, daid);
                    if ( StringUtils.isNotEmpty(fsvale) && ! maxchuzhifangsshi.equals(fsvale)) {
                        return "案卷的处置方式与卷内档案的处置方式不同!";
                    }
                }
            } else if ("x".equals(level)) {
                //判断所有的卷是否审过,不会存在卷审件没审
                int i = isOpenIdentifyMapper.getjiandingnum(new TenantYqKfjdItemFolder().getTableName(), renwuid, daid, jiandingstate);
                if (i > 0) {
                    return "此案卷中存在未经" + ("chushen".equals(type) ? "初审" : "复审") + "过的档案!";
                }
                //获取卷内件最大bgqx
                String maxjnjbgqx = bgqxIdentifyMapper.getmaxjnjbgqx(new TenantYqbgqxjdFolderDa().getTableName(), renwuid, jiandingfield, daid);
                if (StringUtils.isNotEmpty(jdvalue) && (null == maxjnjbgqx || "".equals(maxjnjbgqx))) {
                    return "卷内件未审查!";
                }
                if (!"DQ".equals(jdvalue) && !"CQ".equals(jdvalue) && !"DQ".equals(maxjnjbgqx) && !"CQ".equals(maxjnjbgqx) && StringUtils.isNotEmpty(fsvale)) {
                    if (StringUtils.isNotEmpty(jdvalue) && qcint(maxjnjbgqx) > qcint(jdvalue)) {
                        return "案卷的保管期限不能小于卷内档案的保管期限!";
                    }
                }else {
                    String maxchuzhifangsshi = bgqxIdentifyMapper.getmaxjnjbgqx(new TenantYqbgqxjdFolderDa().getTableName(), renwuid, chuzhifangsshi, daid);
                    if (StringUtils.isNotEmpty(fsvale) && qcint(maxchuzhifangsshi) > qcint(fsvale)) {
                        return "案卷的处置方式与卷内档案的处置方式不同!";
                    }
                }
            }
        }
        isOpenIdentifyMapper.updateshendingnew(tableName, renwuid, daid, jiandingfield, jiandingstate, jdvalue,chuzhifangsshi,fsvale,state);
        if ("chushen".equals(type)) {
            jiandingfield = "FUSHEN_JIANDING";
            jiandingstate = "FUSHEN_STATE";
            chuzhifangsshi = "FUSHEN_CHUZHIFANGSHI";
            isOpenIdentifyMapper.updateshendingnew(tableName, renwuid, daid, jiandingfield, jiandingstate, jdvalue,chuzhifangsshi,fsvale,state);
        }else {
            jiandingfield = "SHENDING_JIANDING";
            jiandingstate = "SHENDING_CHUZHIFANGSHI";
            isOpenIdentifyMapper.updateshendingnew(tableName, renwuid, daid, jiandingfield, jiandingstate, jdvalue,null,null,fsvale);
        }
        return "成功!";
    }

    /**
     * 审定列表
     * @param json
     * @return
     */
    @Override
    public List<Map<String, Object>> sdlist(JSONObject json) {
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null) {
            user = new LoginUser();
            user.setUserId(1L);
        }
        Long renwuid = json.getLong("renwuid");
        Long menuId = json.getLong("menuId");//菜单id
        String chushenresult = json.getString("chushenresult");//鉴定状态
        String fushenresult = json.getString("fushenresult");//初审结果
        String fields = json.getString("fields");//需要查询的字段
        fields = "a.CHUSHEN_CHUZHIFANGSHI, a.FUSHEN_CHUZHIFANGSHI,a.SHENDING_CHUZHIFANGSHI,b.id,b." + fields.replace(",", ",b.");
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        StringBuilder sb = new StringBuilder(" and ");//用于拼接条件
        String orderstr = json.getString("order");//用于排序
        if (null == jsonArray) {
            jsonArray = new JSONArray();
        }
        if(FBswitch){
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            sb.append(" b.MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') and ");
        }
        if (jsonArray.size() > 0) {
            wenjianzhengliService.concatQueryCondition(jsonArray, sb);
        }
        if (null != fushenresult && !"".equals(fushenresult)) {
            sb.append(" a.FUSHEN_CHUZHIFANGSHI ='" + fushenresult+ "' ");
        } else {
            sb.append(" 1=1 ");
        }
        if (null != chushenresult && !"".equals(chushenresult)) {
            sb.append(" and a.CHUSHEN_CHUZHIFANGSHI ='" + chushenresult + "' ");
        } else {
        }
        TenantYqbgqxjdJob yqbgqxjdJob = new TenantYqbgqxjdJob();
        yqbgqxjdJob.setId(renwuid);
        Map<String, Object> getjobinfo = bgqxIdentifyMapper.getjobinfo(yqbgqxjdJob);
        /**处理排序*/
        if (null != orderstr && !"".equals(orderstr)) {
            orderstr = " order by " + orderstr;
        } else {
            int type = -1;
            String tablefield = "";
            String sub = getjobinfo.get("SUB_TABLE_NAME").toString();
            sub = sub.substring(sub.length() - 3, sub.length() - 2);
            if ("F".equalsIgnoreCase(sub)) {//档案层
                type = 0;
                tablefield = "FILE_TABLE_NAME";
            } else if ("V".equalsIgnoreCase(sub)) {//案卷层
                type = 1;
                tablefield = "FOLDER_TABLE_NAME";
            } else if ("X".equalsIgnoreCase(sub)) {//项目层
                type = 3;
                tablefield = "ITEM_TABLE_NAME";
            } else if ("E".equalsIgnoreCase(sub)) {//电子文件层
                type = 1;
                tablefield = "EFILE_TABLE_NAME";
            }
            Map<String, Object> cateinfo = isOpenIdentifyMapper.getcateinfo(new TenantCategory().getTableName(), (String) getjobinfo.get("SUB_TABLE_NAME"), tablefield);
            String applyorderstr = tenantMdataListService.getorder(Long.parseLong(String.valueOf(cateinfo.get("ID"))), menuId, type);
            if (null != applyorderstr && !"".equals(applyorderstr)) {
                orderstr = " order by " + applyorderstr;
            }
        }
        String subtablename = getjobinfo.get("SUB_TABLE_NAME").toString();
        String sub = subtablename.substring(subtablename.length() - 3, subtablename.length() - 2);
        if ("X".equalsIgnoreCase(sub)) {
            subtablename = subtablename.substring(0, subtablename.length() - 3) + "V" + subtablename.substring(subtablename.length() - 2);
        }
        startPage();
        List<Map<String, Object>> sdlist = isOpenIdentifyMapper.sdlist(new TenantYqbgqxjdJobDa().getTableName(), subtablename, renwuid, user.getUserId(), sb.toString(), orderstr, fields, yqbgqxjdJob.getTableName());
        for (Map<String, Object> list: sdlist) {
            if(ObjectUtils.isEmpty(list.get("SHENDING_CHUZHIFANGSHI")) &&ObjectUtils.isNotEmpty(list.get("CHUSHEN_CHUZHIFANGSHI"))
                    &&ObjectUtils.isNotEmpty(list.get("FUSHEN_CHUZHIFANGSHI"))){
                if(list.get("CHUSHEN_CHUZHIFANGSHI").equals(list.get("FUSHEN_CHUZHIFANGSHI"))){
                    list.put("SHENDING_CHUZHIFANGSHI",list.get("FUSHEN_CHUZHIFANGSHI"));
                }
            }
            if(ObjectUtils.isEmpty(list.get("SHENDING_STATE"))){
                if("1".equals(list.get("SHENDING_CHUZHIFANGSHI"))&&ObjectUtils.isNotEmpty(list.get("CHUSHEN_JIANDING"))
                        &&ObjectUtils.isNotEmpty(list.get("CHUSHEN_JIANDING")) && list.get("CHUSHEN_JIANDING").equals(list.get("FUSHEN_JIANDING"))){
                    list.put("SHENDING_JIANDING",list.get("FUSHEN_JIANDING"));
                }else {
                    list.put("SHENDING_JIANDING",null);
                }
            }
        }

        return sdlist;

    }


    /**
     * 审定
     * @param json
     * @return
     */
    @Override
    public int changesdresult(JSONObject json) {
        Long renwuid = json.getLong("renwuid");
        Long daid = json.getLong("daid");
        String bgqx = json.getString("bgqx");
        String fsvalue = json.getString("fsvalue");
        //当选择为销毁时清空审定状态
        if("2".equals(fsvalue))bgqx="";
        Map map = isOpenIdentifyMapper.getdainfo(new TenantYqbgqxjdJobDa().getTableName(), renwuid, daid);
        if (null == map.get("SHENDING_STATE") || "".equals(map.get("SHENDING_STATE"))) {//根据复审结果
            String fushenresult = String.valueOf(map.get("FUSHEN_JIANDING"));
            TenantYqbgqxjdJobDa jobDa = new TenantYqbgqxjdJobDa();
            jobDa.setShendingState(bgqx);
            jobDa.setRenwuid(renwuid);
            jobDa.setDaid(daid);
            jobDa.setShendingchuzhifangshi(fsvalue);
            bgqxIdentifyMapper.updatedatable1(jobDa);
            if ("v".equals(map.get("TYPE"))) {//修改卷内件
                TenantYqbgqxjdFolderDa folderDa = new TenantYqbgqxjdFolderDa();
                folderDa.setShendingState(bgqx);
                folderDa.setRenwuid(renwuid);
                folderDa.setVid(daid);
                folderDa.setShendingchuzhifangshi(fsvalue);
                bgqxIdentifyMapper.updatefolderda1(folderDa);
            }
        } else {//已经改过
            String fushenresult = String.valueOf(map.get("SHENDING_STATE"));
            TenantYqbgqxjdJobDa jobDa = new TenantYqbgqxjdJobDa();
            jobDa.setShendingState(bgqx);
            jobDa.setRenwuid(renwuid);
            jobDa.setDaid(daid);
            jobDa.setShendingchuzhifangshi(fsvalue);
            bgqxIdentifyMapper.updatedatable1(jobDa);
            if ("v".equals(map.get("TYPE"))) {//修改卷内件
                TenantYqbgqxjdFolderDa folderDa = new TenantYqbgqxjdFolderDa();
                folderDa.setShendingState(bgqx);
                folderDa.setRenwuid(renwuid);
                folderDa.setVid(daid);
                folderDa.setShendingchuzhifangshi(fsvalue);
                bgqxIdentifyMapper.updatefolderda1(folderDa);
            }
        }
        return 1;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int jiandingshengxiao(JSONObject json) {
        List jobids = json.getJSONArray("jobids");
        //判断是不是审定完成状态,判断是不是当前人提交的任务
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null) {
            user = new LoginUser();
            user.setUserId(1L);
        }
        List<Map<String, Object>> maps = isOpenIdentifyMapper.getstateanduser(new TenantYqbgqxjdJob().getTableName(), jobids);
        for (int i = 0; i < maps.size(); i++) {
            String state = String.valueOf(maps.get(i).get("JIANDINGSTATE"));
            String userid = String.valueOf(maps.get(i).get("CREATOR"));
            if (!"7".equals(state)) {
                throw new RuntimeException("所选任务中存在非审定完成状态的任务,请重新选择!");
            }
            if (!userid.equals(String.valueOf(user.getUserId()))) {
                throw new RuntimeException("所选任务中存在非当前用户创建的任务,请重新选择!");
            }
            String subTableName = (String) maps.get(i).get("SUB_TABLE_NAME");
            String type = subTableName.substring(subTableName.length() - 3, subTableName.length() - 2);
            String tablename = "";
            if ("X".equalsIgnoreCase(type)) {
                tablename = "ITEM_TABLE_NAME";
            } else if ("V".equalsIgnoreCase(type)) {
                tablename = "FOLDER_TABLE_NAME";
            } else {
                tablename = "FILE_TABLE_NAME";
            }
            String jobdatable = new TenantYqbgqxjdJobDa().getTableName();
            String jobvftable = new TenantYqbgqxjdFolderDa().getTableName();

            //todo 根据状态处置方式判断 是否添加到销毁库
            List<String> faDaId = isOpenIdentifyMapper.selectString(" daid ", "select daid from " +
                    (jobdatable) + " where renwuid =" + maps.get(i).get("ID")+" and SHENDING_CHUZHIFANGSHI = '2' " );

            List<String> vfaDaId = isOpenIdentifyMapper.selectString(" daid ", "select daid from " +
                    (jobvftable) + " where renwuid =" + maps.get(i).get("ID")+" and SHENDING_CHUZHIFANGSHI = '2' " );
            faDaId.addAll(vfaDaId);
            if(faDaId != null && faDaId.size()>0){
                disposeMapper.updateDataNewBgqx(new TenantDispose().getTableName(),faDaId,"xiaohui");
            }
            //获取门类信息
            Map<String, Object> getcateinfo = isOpenIdentifyMapper.getcateinfo(new TenantCategory().getTableName(), subTableName, tablename);

            String idfsql = "select daid from " + jobdatable + " where renwuid=" + maps.get(i).get("ID") +" and SHENDING_CHUZHIFANGSHI = '1' ";
            String nowdate = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            Date jiandingstartdate = DateUtils.parseDate(String.valueOf(maps.get(i).get("JIANDINGSTARTDATE")));
            List<String> sdstate = isOpenIdentifyMapper.selectString(" shending_state ", "select shending_state from " +  ("f".equalsIgnoreCase(type)?jobdatable:jobvftable) + " where renwuid =" + maps.get(i).get("ID") +" and shending_state is not null");

            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            if ("x".equalsIgnoreCase(type)) {//项目类型
                //处理卷
                bgqxIdentifyMapper.updateresult(new TenantYqFolder().getTableName(), "FOLDER_ID", (String) getcateinfo.get("FOLDER_TABLE_NAME"), "ID", idfsql, jobdatable, String.valueOf(maps.get(i).get("ID")), nowdate);
                //处理件
                String idvfsql = "select daid from " + jobvftable + " where vid in(select daid from " + jobdatable + " where renwuid=" + maps.get(i).get("ID") +" and SHENDING_CHUZHIFANGSHI = '1' "+ ")";
                bgqxIdentifyMapper.updateresult(new TenantYqda().getTableName(), "DA_ID", (String) getcateinfo.get("FILE_TABLE_NAME"), "ID", idvfsql, jobvftable, String.valueOf(maps.get(i).get("ID")), nowdate);//修改件主表/件分表
                List<String> strings = isOpenIdentifyMapper.selectString(" daid ", idvfsql);
                if (strings != null && strings.size() > 0 && sdstate != null  && sdstate.size()>0 ) {
                    addBusinessBehavior(strings.stream().collect(Collectors.joining(",")), userid, jiandingstartdate, 0, sdstate.get(0), sysUser);
                }
            } else if ("v".equalsIgnoreCase(type)) {//组卷类型
                //处理卷
                bgqxIdentifyMapper.updateresult(new TenantYqFolder().getTableName(), "FOLDER_ID", (String) getcateinfo.get("FOLDER_TABLE_NAME"), "ID", idfsql, jobdatable, String.valueOf(maps.get(i).get("ID")), nowdate);
                //处理件
                String idvfsql = "select daid from " + jobvftable + " where vid in(select daid from " + jobdatable + " where renwuid=" + maps.get(i).get("ID") +" and SHENDING_CHUZHIFANGSHI = '1' "+ ")";
                bgqxIdentifyMapper.updateresult(new TenantYqda().getTableName(), "DA_ID", (String) getcateinfo.get("FILE_TABLE_NAME"), "ID", idvfsql, jobvftable, String.valueOf(maps.get(i).get("ID")), nowdate);//修改件主表/件分表
                List<String> strings = isOpenIdentifyMapper.selectString(" daid ", idvfsql);
                if (strings != null && strings.size() > 0&& sdstate != null  && sdstate.size()>0) {
                    addBusinessBehavior(strings.stream().collect(Collectors.joining(",")), userid, jiandingstartdate, 0, sdstate.get(0), sysUser);
                }
            } else if ("f".equalsIgnoreCase(type)) {//组件类型
                bgqxIdentifyMapper.updateresult(new TenantYqda().getTableName(), "DA_ID", (String) getcateinfo.get("FILE_TABLE_NAME"), "ID", idfsql, jobdatable, String.valueOf(maps.get(i).get("ID")), nowdate);//修改件主表/件分表
            }
            TenantYqbgqxjdJob job = new TenantYqbgqxjdJob();
            job.setId(Long.parseLong(String.valueOf(maps.get(i).get("ID"))));
            job.setJiandingenddate(nowdate);
            job.setJiandingstate(8);
            bgqxIdentifyMapper.updatejobinfo(job);
            TenantYqbgqxjdTask task = new TenantYqbgqxjdTask();
            task.setRenwuid(Long.parseLong(String.valueOf(maps.get(i).get("ID"))));
            task.setStatus(8);
            task.setCaozuoren(String.valueOf(user.getUserId()));
            task.setEndtime(nowdate);
            bgqxIdentifyMapper.updatetask(task);
            //过程信息
            List<String> stringsId = isOpenIdentifyMapper.selectString(" daid ", idfsql);
            if (stringsId != null && stringsId.size() > 0 && sdstate != null  && sdstate.size()>0) {
                if ("f".equalsIgnoreCase(type)) {
                    addBusinessBehavior(stringsId.stream().collect(Collectors.joining(",")), userid, jiandingstartdate, 0, sdstate.get(0), sysUser);
                } else {
                    addBusinessBehavior(stringsId.stream().collect(Collectors.joining(",")), userid, jiandingstartdate, 1, sdstate.get(0), sysUser);
                }
            }
        }

        return 1;
    }

    @Override
    public List<Map<String, Object>> bgqxjdjoblist(JSONObject json) {
        String title = json.getString("title");
        if (null != title) {
            title = title.replace(" ", "");
        }
        String starttime = json.getString("starttime");
        String endtime = json.getString("endtime");
        Integer state = json.getInteger("state");
        String qzh = json.getString("qzh");
        String order = json.getString("order");
        if (null == order || "".equals(order)) {
            order = " order by ac.create_time  desc";
        } else {
            order = " order by " + order;
        }
        return isOpenIdentifyMapper.kfjdjoblistnew(title, starttime, endtime, state, qzh, new TenantYqbgqxjdJob().getTableName(), order);
    }

    @Override
    public List<Map<String, Object>> tongji(JSONObject json) {
        String type = json.getString("type");
        List<TenantSysDictData> bgqxs = dictTypeService.selectDictDataByType("BGQX");
        if ("jobname".equals(type)) {
            return bgqxIdentifyMapper.gettongjibyjobname(new TenantYqda().getTableName(), new TenantYqbgqxjdJob().getTableName(), new TenantYqbgqxjdJobDa().getTableName()
                    , new TenantYqbgqxjdFolderDa().getTableName(), new TenantCategory().getTableName(), bgqxs);
        } else if ("user".equals(type)) {
            String level = json.getString("level");
            String userid = json.getString("userid");
            if ("chushen".equals(level)) {
                return bgqxIdentifyMapper.gettongjibyuserchushen(new TenantYqda().getTableName(), new TenantYqbgqxjdJob().getTableName(), new TenantYqbgqxjdJobDa().getTableName()
                        , new TenantYqbgqxjdFolderDa().getTableName(), new TenantCategory().getTableName(), userid, bgqxs);
            } else {
                return bgqxIdentifyMapper.gettongjibyuserfushen(new TenantYqda().getTableName(), new TenantYqbgqxjdJob().getTableName(), new TenantYqbgqxjdJobDa().getTableName()
                        , new TenantYqbgqxjdFolderDa().getTableName(), new TenantCategory().getTableName(), userid, bgqxs);
            }

        } else if ("category".equals(type)) {
            return bgqxIdentifyMapper.gettongjibycate(new TenantYqda().getTableName(), new TenantYqbgqxjdJob().getTableName(), new TenantYqbgqxjdJobDa().getTableName()
                    , new TenantYqbgqxjdFolderDa().getTableName(), new TenantCategory().getTableName(), bgqxs);
        } else if ("qzh".equals(type)) {
            return bgqxIdentifyMapper.gettongjibyqzh(new TenantYqda().getTableName(), new TenantYqbgqxjdJob().getTableName(), new TenantYqbgqxjdJobDa().getTableName()
                    , new TenantYqbgqxjdFolderDa().getTableName(), new TenantCategory().getTableName(), bgqxs);
        }
        return null;
    }


    // @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletedata(List<Long> ids, String cztype) {
        disposeMapper.deletedata(ids,cztype,new TenantDispose().getTableName());
        return 1;
    }

    private int qcint(String str) {
        String numStr = str.replaceAll("[^\\d]", "");
        int num = Integer.parseInt(numStr);
        return num;
    }
    /**
     * 添加过程信息
     *
     * @param daIds
     * @param userid
     */
    @Async
    public void addBusinessBehavior(String daIds, String userid, Date date, int type, String state, SysUser sysUser) {
        String[] split = daIds.split(",");
        SysUser sysUserHis = remoteUserService.selectUserById(Long.parseLong(userid));
        String tablename = "";
        String daId = "DA_ID";
        if (1 == type) {
            tablename = SecurityUtils.getTenantCode() + Constants.BIG_TABLE_YQFOLDER;
            daId = "FOLDER_ID";
        } else {
            tablename = SecurityUtils.getTenantCode() + Constants.BIG_TABLE_YQDA;
        }
        List<Map<String, Object>> isOpens = isOpenIdentifyMapper.getdictdata("BGQX", sysUser.getTenantCode() + "_DICT_DATA");
        for (String id : split) {
            List<String> strings = isOpenIdentifyMapper.selectString(" BGQX ", " select BGQX from " + tablename + " where " + daId + " = '" + id + "' ");
            String dictLabel = "无";
            if (strings != null && strings.size() > 0 &&strings.get(0)!= null) {
                List<String> labels = isOpens.stream().filter(p -> strings.get(0).equals(p.get("DICT_VALUE"))).map(m -> m.get("DICT_LABEL").toString()).collect(Collectors.toList());
                if (labels != null && labels.size() > 0) dictLabel = labels.get(0);
            }
            String sdLable = isOpens.stream().filter(p -> state.equals(p.get("DICT_VALUE"))).map(m -> m.get("DICT_LABEL").toString()).collect(Collectors.toList()).get(0);
            BusinessBehaviorUtil.addIdentify(Long.parseLong(id), BusinessBehavior.BGQXJDSX, sysUser, DateUtils.getNowDate(), "续存保管期限："+sdLable);
            BusinessBehaviorUtil.addIdentify(Long.parseLong(id), BusinessBehavior.BGQXJDFQ, sysUserHis, date,"原保管期限："+ dictLabel);
        }
    }


}
